<?php
namespace App\Http\Controllers\Api\Ant;

use App\Http\Controllers\Controller;
use App\User;
use App\UserCoinLog;
use App\GameZghpt;
use App\Jobs\JoinTeam;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 欢乐餐厅
 *
 * @version 1.0.0
 */
class AntController extends Controller {

    // 欢乐餐厅
    const bussiness_id  = 8;

    protected $wechat;

    //奖励层级
    private $reward_count = 2;

    public function __construct() {
        $this->wechat = app('wechat');
    }

    /**
     * 初始化餐厅各楼层队伍，仅初始化一次
     *
     * @return [type] [description]
     */
    public function initData() {
        if ($redis->set('ant:init:team', time(), ['nx'])) {
            $init_teams = DB::table('game_ant_team')->whereIn('tid', [1, 2, 3, 4, 5, 6, 7, 8])->get();
            $redis = $this->getRedis();
            foreach($init_teams as $init_team) {
                $uids = json_decode($init_team['uid_list'], true);
                for($i=0; $i<15; $i++) {
                    $redis->rPush("ant:team:$i", $uids[$i]);
                }
            }
            return $this->echoJson(0, '初始化成功');
        }
        return $this->echoJson(0, '已经初始化，请勿重复操作');
    }

    /**
     * 加入欢乐餐厅[测试]
     *
     * @return [type] [description]
     */
    public function joinTeam(Request $request) {

        // 检察参数
        // for($i=20001; $i<=20002; $i++) {
        //     dispatch(new JoinTeam($i));
        // }

        return $this->echoJson(0, '');
    }

    /**
     * 获取用户个人信息
     *
     * @return [type] [description]
     */
    public function getUserInfo() {
        $uid = $this->getLoginUser();
        DB::setFetchMode(\PDO::FETCH_ASSOC);
        $user = DB::table('user')->where('id', $uid)->first();
        $user['XYB'] = UserCoinLog::totalXyb($user['id']) * 100;

        $team = [];
        $ant_user = DB::table('game_ant_user')->where('uid', $uid)->first();
        if (!empty($ant_user) && !empty($ant_user['team_id'])) {
            $team_id = $ant_user['team_id'];
            $team = DB::table('game_ant_team')->where('tid', $team_id)->first();
            $uid_list = json_decode($team['uid_list'], true);
            $user_list = DB::table('game_ant_user')->whereIn('uid', $uid_list)->get()->toArray();
            $user_list = array_combine(array_map(function($item) {
                return $item['uid'];
            }, $user_list), array_values($user_list));
            $sort_user_list = [];
            $uid_idx = -1;
            foreach($uid_list as $key => $val) {
                if (!empty($user_list[$val])) {
                    array_push($sort_user_list, $user_list[$val]);
                }
                if ($uid == $val) {
                    $uid_idx = intval($key) + 1;
                }
            }
            $layer = 5;
            if ($uid_idx == 1) {
                $layer = 1;
            } else if ($uid_idx >= 2 && $uid_idx <= 3) {
                $layer = 2;
            } else if ($uid_idx >= 4 && $uid_idx <= 7) {
                $layer = 3;
            } else if ($uid_idx >= 8 && $uid_idx <= 15) {
                $layer = 4;
            } else if ($uid_idx >= 16 && $uid_idx <= 31) {
                $layer = 5;
            }
            $join_num  = max(intval($team['count']) - 15, 0);
            $ant_user['layer']    = $layer;
            $ant_user['join_num'] = $join_num;
            $team['uid_list'] = $sort_user_list;
        }
        $user['team'] = $team;
        $user['ant_user'] = $ant_user;
        $this->echoJson(0, '', $user);
    }

    /**
     * 批量更新多用户小妖币
     *
     * @param  [type] $uid  [description]
     * @param  [type] $gold [description]
     * @return [type]       [description]
     */
    private function batchUpdateUserXYB($uid_list , $gold) {
        foreach($uid_list as $uid) {
            $key = sprintf("%s-%s-%s-%s", self::bussiness_id, $uid, $gold, time());
            $tips = $gold > 0 ? '蚂蚁特工队赢得小妖币' : '蚂蚁特工队消耗小妖币';
            UserCoinLog::log(self::bussiness_id, $uid, UserCoinLog::TYPE_XYB, $gold, $tips, $key);
        }
    }

    /**
     * 更新用户小妖币
     *
     * @param  [type] $uid  [description]
     * @param  [type] $gold [description]
     * @return [type]       [description]
     */
    private function updateUserXYB($uid, $gold) {
        $key = sprintf("%s-%s-%s-%s", self::bussiness_id, $uid, $gold, time());
        $tips = $gold > 0 ? '蚂蚁特工队赢得小妖币' : '蚂蚁特工队消耗小妖币';
        UserCoinLog::log(self::bussiness_id, $uid, UserCoinLog::TYPE_XYB, $gold, $tips, $key);
    }

    /**
     * 统计当日盈亏（记录保留7天）
     *
     * @param  [type] $gold [description]
     * @return [type]       [description]
     */
    private function statDayProfitAndLoss($gold) {
        $redis = $this->getRedis();
        $day_stat_key = sprintf("hlgc:stat:%s", date('Ymd', time()));
        $redis->incrBy($day_stat_key, $gold);
        $redis->setTimeout($day_stat_key, 7*24*60*60);
    }

    /**
     * 概率算法
     *
     * @param  [type] $rand [description]
     * @return [type]       [description]
     */
    private function get_rand($rand) {
        $result = '';
        //概率数组的总概率精度
        $sum = 0;
        foreach ($rand as $v) {
            $sum += $v['rate'] * 100;
        }
        //概率数组循环
        foreach ($rand as $v) {
            $rate = $v['rate'] * 100;
            //抽取随机数
            $rand_num = mt_rand(1, $sum);
            if ($rand_num <= $rate) {
                //得出结果
                $result = $v['id'];
                break;
            } else {
                $sum -= $rate;
            }
        }
        unset ($rand);
        return $result;
    }

    /**
     * 告警（短信）
     *
     * @param  string $phone   [电话]
     * @param  string $message [信息]
     * @return [type]          [description]
     */
    private function alarmSms($phone = '15011931913', $message = '告警邮件') {
        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "http://sms-api.luosimao.com/v1/send.json");
            curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 8);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_HEADER, FALSE);
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($ch, CURLOPT_USERPWD, 'api:key-5145112f10b704bbd5592f80402c77b5');
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, array('mobile' => $phone, 'message' => $message));
            $res = curl_exec($ch);
            curl_close( $ch );
        } catch (\Exception $e) {
            Log::warn("发送告警邮件失败！" . $e->getMessage());
        }
    }

    /**
     * 验证登录
     *
     * @return [type] [description]
     */
    private function getLoginUser() {
        // 检查用户登录态
        $user = auth()->user();
        $uid = $user->id;
        return $uid;
    }

    /**
     * 获取Redis实例
     *
     * @return [type] [description]
     */
    private function getRedis() {
        static $redis = null;
        if (empty($redis)) {
            $redis = new \Redis();
            $redis->connect(env('REDIS_HOST'), env('REDIS_PORT'));
            $redis->auth(env('REDIS_PASSWORD'));
        }
        return $redis;
    }

    /**
     * 响应JSON/JSONP格式数据
     *
     * @param  integer $code [返回代码：0 成功 1 失败]
     * @param  string  $msg  [错误信息]
     * @param  array   $data [返回数据]
     * @return [type]        [description]
     */
    private function echoJson($code = 0, $msg = '', $data = []) {
        header('Content-type: application/json');
        $result = [
            'code'  => $code,
            'msg'   => $msg,
            'data'  => $data,
        ];
        $json = json_encode($result);

        // JSONP
        if (!empty($_GET['callback'])) {
            $json = $_GET['callback'] . "(" . $json . ")";
        }
        echo $json;
        exit(0);
    }

    /**
     * 奖励上级
     */
    public function rewardFinder($user, $total) {
        if ($this->reward_count) {
            if ($finder = User::where('id', $user['finder_id'])->first()) {
                if (floatval($xyb = bcmul($total, 0.01, 2))) {
                    if(!$gameZghpt = $finder->game_zghpt){
                        $gameZghpt = new GameZghpt();
                        $gameZghpt->user_id = $finder->id;
                        $gameZghpt->quota = 0;
                        $gameZghpt->level = 0;
                        $gameZghpt->save();
                    }
                    if($gameZghpt->level) {
                        $tmp_xyb = $xyb * 100;
                        $message = '恭喜您获得' . $tmp_xyb . '个小妖币的推荐奖励。';

                        $key = '8-'. $finder->id . '-' . $xyb . '-' . time() . '-1';
                        UserCoinLog::log( 8, $finder->id, UserCoinLog::TYPE_XYB, $xyb, '推荐奖励', $key );
                    } else {
                        $message = '您好，您错过了'. $xyb .'小妖币的红包，请<a href="http://ga.cloudxt.cn/zghpt/vip/page">立即升级VIP</a>！';
                    }

                    $this->dispatch(new SendWechatMessage($finder->openid, $message));

                    $this->reward_count--;
                    $this->rewardFinder($finder, $total);
                }
            }
        }
    }

}
